<template>
  <base-modal
    :title="$t('task.setting.taskTypeSetting.manage.title9')"
    width="450px"
    @cancel="cancel"
    :show.sync="isShow"
    :mask-closeable="false">
    <div class="choose-team">
      <el-input
        style="margin-bottom: 22px"
        :placeholder="$t('common.base.inputKeywordToSearch')"
        prefix-icon="el-icon-search"
        @input="search"
        v-model="keyword">
      </el-input>
      <el-tree
        v-loading="loading"
        :data="teamList"
        show-checkbox
        @check="handleCheck"
        default-expand-all
        :default-checked-keys="checkedTeamList"
        node-key="id"
        ref="teamTree"
        highlight-current
        check-strictly
        :props="defaultProps">
      </el-tree>
    </div>
    <el-row class="choose-team-footer" type="flex" justify="space-between" slot="footer">
      <el-checkbox v-model="flag" @change="checkAll" :disabled="loading">{{$t('common.base.selectAll')}}</el-checkbox>
      <div>
        <el-button @click="cancel">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" :loading="pedding" @click="update">{{$t('common.base.makeSure')}}({{$t('task.list.components.selected')}}{{checkedTeamList.length}})</el-button>
      </div>
    </el-row>
  </base-modal>
</template>

<script>
import _ from 'lodash';

/** api */
import * as TeamApi from '@src/api/TeamApi';
import * as SettingApi from '@src/api/SettingApi.ts';

export default {
  name: 'choose-team-dialog',
  props: {
    id: {
      type: String,
      default: ''
    },
    visiable: {
      type: Boolean,
      default: false
    },
    value: {
      type: Array,
      default: () => []
    },
    nodeArr: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: ()=> 'task'
    }
  },
  data() {
    return {
      isShow: false,
      keyword: '',
      flag: false,
      teamList: [],
      teamIds: [],
      checkedTeamList: [],
      checkedTeamObjList: [],
      loading: false,
      pedding: false
    }
  },
  computed: {
    defaultProps() {
      return {
        children: 'children',
        label: 'tagName'
      }
    }
  },
  watch: {
    visiable(newVal){
      this.isShow = newVal;
      if(newVal) {
        this.checkedTeamList = this.value;
        this.checkedTeamObjList = this.nodeArr
        this.keyword = '';
        this.fetchTagList();
      }
    },
  },
  methods: {
    cancel() {
      this.$emit('update:visiable', false);
    },
    update() {
      let params = {
        id: this.id,
        tagIds: this.checkedTeamList.length === 0 ? '' : this.checkedTeamList.join(','),
        tagIdsArr: this.checkedTeamList
      };
      // 事件的直接return
      // if(this.type === 'event') {
      this.$emit('update', { checkedTeamList: this.checkedTeamList, checkedTeamObjList: this.checkedTeamObjList, requestParams: params });
      this.cancel();
        // return
      // }

      // this.pedding = true;
      // SettingApi.changeTags(params).then(res => {
      //   this.pedding = false;
      //   this.$emit('update', this.checkedTeamList);
      //   this.cancel();
      // }).catch(err => {
      //   console.log('changeTag => err', err);
      // })
      //   .finally(() => {
      //     this.pedding = false;
      //   })
    },
    fetchTagList(keyword = '') {
      let params = {
        keyword,
        onlyParent: true,
        pageNum: 1,
        pageSize: 50
      }
      this.loading = true;
      TeamApi.tagList(params).then(res => {
        this.teamList = res.list;
        this.teamIds = this.getTeamIds(res.list);
                
        if(this.teamList.length === 0) {
          this.flag = 0;
          return;
        }
        this.flag = !this.teamIds.some(teamId => !this.checkedTeamList.includes(teamId));
      }).catch(err => {
        console.error('getTagList => error', err);
      })
        .finally(() => {
          this.loading = false;
        })
    },
    search: _.debounce(function(keyword) {
      this.fetchTagList(keyword);
    }, 300),
    handleCheck(data, checkObj) {
      this.checkedTeamList = [
        ...new Set([
          ...this.checkedTeamList.filter(item => !this.teamIds.includes(item)),
          ...checkObj.checkedKeys
        ])
      ];

      // 组合对象的数组（不是只有id的数组）
      const checkedNodes = checkObj?.checkedNodes || []
      this.checkedTeamObjList = this.deduplicationObjArr([
        ...this.checkedTeamObjList.filter(item => !this.teamIds.includes(item.id)),
        ...checkedNodes
      ])

      this.flag = !this.teamIds.some(teamId => !this.checkedTeamList.includes(teamId));
    },
    checkAll(flag) { // 全选或反选
      let checkedTeamList = []
      let checkedTeamObjList = []
      this.flag = flag;

      if(flag) {
        this.$refs.teamTree.setCheckedNodes(this.teamList);
        checkedTeamList = [...new Set([...this.checkedTeamList, ...this.teamIds])];
        checkedTeamObjList = this.deduplicationObjArr([...this.checkedTeamObjList, ...this.getTeamItems(this.teamList)])
      }else {
        checkedTeamList = this.checkedTeamList.filter(item => !this.teamIds.includes(item));
        checkedTeamObjList = this.checkedTeamObjList.filter(item => !this.teamIds.includes(item.id))
        this.$refs.teamTree.setCheckedNodes([]); 
      }

      this.checkedTeamObjList = checkedTeamObjList

      this.checkedTeamList = checkedTeamList;
    },
    /**
     * 描述 去重
     * @date 2023-02-10
     * @param {any} nodeArr
     * @returns {any}
     */
    deduplicationObjArr(nodeArr) {
      return nodeArr.reduce((prev, cur)=> {
        const existItem = prev.find(nodeItem => nodeItem.id === cur.id)
        if(!existItem) prev.push(cur)
        return prev
      }, [])
    },
    getTeamIds(list) { // 获取所有团队id（包括子级）
      let ids = [];
      list.map(item => {
        if(item.children && item.children.length > 0) {
          let childIds = this.getTeamIds(item.children);
          ids = ids.concat(childIds);
        }

        ids.push(item.id);
      })
      return ids;
    },

    getTeamItems(list) { // 获取所有团队（包括子级）
      let items = [];
      list.map(item => {
        if(item.children && item.children.length > 0) {
          let childItems = this.getTeamItems(item.children);
          items = items.concat(childItems);
        }

        items.push(item);
      })
      return items;
    }
  }
}
</script>

<style lang="scss" scoped>
.choose-team{
    height: 437px;
    padding: 20px;
    overflow: auto;
}

.choose-team-footer{
    width: 100%;
    line-height: 32px;
}

/** element-ui */
::v-deep .el-checkbox{
  margin-bottom: 4px;
}
</style>